package com.kasax.utils;

import android.content.Context;
import android.os.Build;
import android.os.Environment;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FileUtils {

    public static String getSafeSdcardPath(String src) {
        String result = src;
        if (src.startsWith("/mnt/sdcard")) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // 针对android 11以上的处理
                String storageDirPath = Environment.getExternalStorageDirectory().getPath();
                String newPath = src.replace("/mnt/sdcard", storageDirPath);
                result = newPath;
            }
        }
        LogUtils.e("getSafeSdcardPath result = " + result);
        return result;
    }

    /**
     * 获取下载路径
     */
    public static String getUpgradePath() {
        String filePath = getAppRootPath();
        File file = new File(filePath);
        if (!file.isDirectory()) {
            file.mkdirs();
        }
        file = null;
        return filePath;
    }

    public static String getAppRootPath() {
        String filePath = "/downloads";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
                filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + filePath;
            } else {
                filePath = "/mnt/sdcard/downloads";
            }
        } else {
            filePath = Utils.getApp().getCacheDir() + filePath;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        file = null;
        File nomedia = new File(filePath + "/.nomedia");
        if (!nomedia.exists())
            try {
                nomedia.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return filePath;
    }

    /**
     * 写入文件
     */
    public static void write(String data, String filePath) {
        LogUtils.d("FileUtils write exec");
        File tFile = new File(filePath);
        try {
            if (!tFile.exists()) {
                tFile.createNewFile();
            }
            try (FileWriter fw = new FileWriter(tFile)) {
                fw.write(data);
                fw.flush();
                fw.close();
                LogUtils.d("FileUtils write exec complete");
            } catch (Throwable e) {
                LogUtils.e(e);
            }
        } catch (Throwable e) {
            LogUtils.e(e);
        }
    }

    /**
     * 读取文件
     *
     * @param filePath
     * @return
     */
    public static String readString(String filePath) {
        LogUtils.d("FileUtils readString exec");
        File tFile = new File(filePath);
        StringBuilder sb = new StringBuilder();
        if (!tFile.exists()) {
            return sb.toString();
        }
        try (BufferedReader br = new BufferedReader(new FileReader(tFile))) {
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            LogUtils.d("FileUtils readString exec compile");
        } catch (Throwable e) {
            LogUtils.e(e);
        }
        return sb.toString();
    }

    private static String ins2Str(InputStream ins) {
        BufferedReader br = new BufferedReader(new InputStreamReader(ins));
        String line = null;
        StringBuffer sb = new StringBuffer();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\r\n");
            }
        } catch (IOException e) {
            LogUtils.e(e);
        }
        return sb.toString();
    }

    public static String readStrWithAssets(Context context, String fileName) {
        String data = null;
        try (InputStream ins = context.getAssets().open(fileName)) {
            data = ins2Str(ins);
        } catch (IOException e) {
            LogUtils.e(e);
        }
        return data;
    }


    /**
     * 获取外部存储目录，一般是/sdcard/ 如果不存在，就返回/data/
     */
    public static File getDataRoot() {
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ||
                    (Environment.getExternalStorageDirectory().exists() && Environment.getExternalStorageDirectory().canWrite())) {
                return Environment.getExternalStorageDirectory();
            } else {
                return Environment.getDataDirectory();
            }
        } catch (Exception e) {
            return null;
        }
    }

    public static void deleteFile(File file, FileFilter fileFilter) {
        if (file == null) {
            return;
        }
        if (!fileFilter.accept(file)) {
            return;
        }
        if (file.isFile()) {
            file.delete();
            return;
        }
        File[] files = file.listFiles();
        if (files == null) {
            file.delete();
            return;
        }
        for (File childFile : files) {
            deleteFile(childFile, fileFilter);
        }
        file.delete();
    }


}
